﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using mshtml;
using Microsoft.Win32;
using Application = System.Windows.Application;
using ContextMenu = System.Windows.Forms.ContextMenu;
using MenuItem = System.Windows.Forms.MenuItem;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Forms.MouseEventArgs;
using MouseEventHandler = System.Windows.Forms.MouseEventHandler;
using UserControl = System.Windows.Controls.UserControl;
using WebBrowser = System.Windows.Controls.WebBrowser;

namespace doubanfm
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private NotifyIcon _notifyIcon;
        readonly DispatcherTimer _dispatcherTimer = new System.Windows.Threading.DispatcherTimer { Interval = new TimeSpan(0, 0, 1) };
        private WebBrowser _tempBrowser;
        private WebBrowser _closeBrowser;
        public MainWindow()
        {
            CreateIe9();
            InitializeComponent();
            _tempBrowser = UWebBrowser;
            _closeBrowser = UWebBrowser;
            _tempBrowser.Navigated += CancleErrorJscript;
            _dispatcherTimer.Tick += (sender, er) =>
            {
                WebReset();
            };
            this.Loaded += (sender, er) =>
            {
                _tempBrowser.Source = new Uri("http://douban.fm/");
                _tempBrowser.LoadCompleted += (s, e) =>
                {
                    _dispatcherTimer.Start();

                };
            };
        }


        private void CreateIe9()
        {
            try
            {
                const string ketpath =
                  @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";

                using (var localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
                    RegistryView.Registry64))
                {
                    using (var src = localKey.OpenSubKey(ketpath, true))
                    {
                        var names = src.GetValueNames();
                        src?.SetValue("Doubanfm.exe", 9000, RegistryValueKind.DWord);
                    }
                }

                using (var localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
                    RegistryView.Registry32))
                {
                    using (var src = localKey.OpenSubKey(ketpath, true))
                    {
                        src?.SetValue("Doubanfm.exe", 9000, RegistryValueKind.DWord);
                    }
                }
            }
            catch (Exception)
            {
               
            }
        }


        #region 托盘


        private void NotifyIcon()
        {
            this.Visibility = Visibility.Hidden;
            if (_notifyIcon != null) return;
            this._notifyIcon = new NotifyIcon
            {
                BalloonTipText = @"DouBan FM",
                Text = @"DouBan FM",
                Visible = true,
            };

            var streamResourceInfo =
                Application.GetResourceStream(
                    new Uri("pack://application:,,,/doubanfm;component/Resource/Image/ClockiConk.ico"));
            if (streamResourceInfo != null)
            {
                Stream iconStream = streamResourceInfo.Stream;
                _notifyIcon.Icon = new System.Drawing.Icon(iconStream);
            }
            this._notifyIcon.ShowBalloonTip(1000);
            this._notifyIcon.MouseClick += new MouseEventHandler(notifyIcon_MouseClick);
            var item2 = new MenuItem("Exit");
            item2.Click += new EventHandler(item2_Click);
            var menuItems = new MenuItem[] {item2};
            this._notifyIcon.ContextMenu = new ContextMenu(menuItems);
            this.StateChanged += new EventHandler(MainWindow_StateChanged);
            this.Closing += MainWindow_Closing;
        }


        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visibility == Visibility.Visible)
                {
                    this.Visibility = Visibility.Hidden;
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                    this.Activate();
                }
            }
        }


   
        private void item2_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void MainWindow_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.Visibility = Visibility.Hidden;
            }
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (System.Windows.MessageBox.Show("Do you want exit Luminous？",
                                               "Luminous",
                                               MessageBoxButton.YesNo,
                                               MessageBoxImage.Question,
                                               MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                this._notifyIcon.Visible = false;
                Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        #endregion


        private void Close(object sender, RoutedEventArgs e)
        {
            _notifyIcon = null;
            Environment.Exit(0);
        }

        private void TipPan(object sender, RoutedEventArgs e)
        {
            NotifyIcon();
        }

        private void Minset(object sender, RoutedEventArgs e)
        {
           this.WindowState=WindowState.Minimized;
        }


        /// <summary>
        /// Handles the OnMouseLeftButtonUp event of the UIElement control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
        private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WebReset();
        }

        /// <summary>
        /// Handles the OnMouseLeftButtonUp2 event of the UIElement control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
        private void UIElement_OnMouseLeftButtonUp2(object sender, MouseButtonEventArgs e)
        {
            _closeBrowser.Dispose();
            _tempBrowser = new WebBrowser() { Source = new Uri("http://douban.fm/")};
            _tempBrowser.Navigated += CancleErrorJscript;
            Window winw = new Window {Content = _tempBrowser};
            winw.Show();
            winw.Closed += (sender1, er) =>
            {
                _tempBrowser.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                _tempBrowser.Height = 360;
                _tempBrowser.Width = 520;
                _tempBrowser.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                _tempBrowser.Margin =new Thickness(35,110,0,0);
                winw.Content = null;
                Grid.Children.RemoveAt(Grid.Children.Count-1);
                Grid.Children.Add(_tempBrowser);
                _closeBrowser = _tempBrowser;
                _dispatcherTimer.Start();
            };
        }



        /// <summary>
        /// Cancles the error jscript.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Navigation.NavigationEventArgs"/> instance containing the event data.</param>
        public void CancleErrorJscript(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            var fiComWebBrowser = typeof (WebBrowser).GetField("_axIWebBrowser2",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            if (fiComWebBrowser == null)
                return;

            object objComWebBrowser = fiComWebBrowser.GetValue(sender);
            if (objComWebBrowser == null)
                return;

            objComWebBrowser.GetType()
                .InvokeMember("Silent", System.Reflection.BindingFlags.SetProperty, null, objComWebBrowser,
                    new object[] {true});
        }



        /// <summary>
        /// Webs the reset.
        /// </summary>
        private void WebReset()
        {
            _dispatcherTimer.Stop();
    
            if (_tempBrowser.Document == null) return;
            mshtml.IHTMLDocument2 dom = (mshtml.IHTMLDocument2) _tempBrowser.Document;
         
            if (dom == null) return;

            dom.body.setAttribute("scroll", "yes"); //禁用浏览器的滚动条 
           
            var removeclase = new List<string>() {"nav-logo", "feedback","fr", "explore" , "tips" , "q7sVUCVH_o9AZe1H03951" };

            foreach (IHTMLElement element in dom.all)
            {
     
                var classname = element.className;
                if (classname == "_2v_c01woP-q49Tpi3piSHr"||classname== "link-close")
                {
                    element.click();
                    WebReset();
                }

                if (classname == "middle")
                {
                    var midelenodel = element as IHTMLDOMNode;
                    midelenodel?.firstChild.removeNode(true);
                }



                //set background
                if (element.id == "app")
                {
                    element.style.backgroundColor = "rgba(250, 250, 250, 0.933333);";
                }

                //remove
                if (!removeclase.Contains(classname)) continue;
                var enodel = element as IHTMLDOMNode;
                enodel?.removeNode(true);
                
            }
            //dom.parentWindow.scrollTo(1565, 0);

        }



        /// <summary>
        /// Handles the OnMouseLeftButtonDown event of the UIElement control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        public void UIElement_OnMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }


    }

      
}
